package com.feiyisys.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feiyisys.common.Result;
import com.feiyisys.entity.Activity;
import com.feiyisys.entity.CulturalHeritage;
import com.feiyisys.entity.User;
import com.feiyisys.mapper.ActivityMapper;
import com.feiyisys.mapper.CulturalHeritageMapper;
import com.feiyisys.mapper.UserMapper;
import com.feiyisys.service.ActivityService;
import com.feiyisys.service.CulturalHeritageService;
import com.feiyisys.vo.ActivityRegistrationStatVo;
import com.feiyisys.vo.CategoryCountVo;
import com.feiyisys.vo.DashboardDataVo;
import com.feiyisys.vo.RegistrationStat;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/dashboard")
@Tag(name = "仪表盘")
@Slf4j
@CrossOrigin("*")
public class DashboardController {
    @Resource
    private CulturalHeritageMapper culturalHeritageMapper;
    @Resource
    private UserMapper  userMapper;
    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private ActivityService activityService;

    @GetMapping("/getDashboardData")
    public Result<DashboardDataVo> getDashboardData() {
        Wrapper<CulturalHeritage> culturalHeritageWrapper = new QueryWrapper<>();
        Long heritageCount = culturalHeritageMapper.selectCount(culturalHeritageWrapper);
        log.info(" culturalHeritageCount: {}", heritageCount);

        Wrapper<User> userWrapper = new QueryWrapper<>();
        Long userCount = userMapper.selectCount(userWrapper);
        log.info(" userCount: {}", userCount);

        Wrapper<Activity> activityWrapper = new QueryWrapper<>();
        // 获取活动数量
        Long activityCount = activityMapper.selectCount(activityWrapper);
        log.info(" activityCount: {}", activityCount);
        // 获取报名人数总和（假设字段名为 registration_count）
        Long totalRegistration = activityMapper.selectSum("current_participants", activityWrapper);
        log.info(" totalRegistration: {}", totalRegistration);
        DashboardDataVo dashboardDataVo = new DashboardDataVo();
        dashboardDataVo.setHeritageCount(heritageCount);
        dashboardDataVo.setUserCount(userCount);
        dashboardDataVo.setActivityCount(activityCount);
        dashboardDataVo.setTotalRegistration(totalRegistration);
        return Result.success(dashboardDataVo);
    }

    @GetMapping("/getfenleiInfo")
    public Result<List<CategoryCountVo>> getfenleiInfo() {
        List<CategoryCountVo> categoryStats = culturalHeritageMapper.selectCategoryStatistics();
        return Result.success(categoryStats);
    }

    @GetMapping("/getActivityRegistrations")
    public Result<ActivityRegistrationStatVo> getActivityRegistrations(@RequestParam(required = false, defaultValue = "7d") String range) {
        // 验证参数范围
        if (!"7d".equals(range) && !"30d".equals(range)) {
            range = "7d"; // 默认值
        }

        // 获取统计数据 - 修改为正确的类型
        List<RegistrationStat> rawData = activityMapper.selectRegistrationStatsByRange(range);

        // 处理数据，生成完整的日期序列
        ActivityRegistrationStatVo statVo = generateCompleteDateSeries(rawData, range);

        return Result.success(statVo);
    }

    /**
     * 生成完整的日期序列数据
     */
    private ActivityRegistrationStatVo generateCompleteDateSeries(List<RegistrationStat> rawData, String range) {
        ActivityRegistrationStatVo statVo = new ActivityRegistrationStatVo();
        List<String> dates = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();

        // 计算天数
        int days = 7;
        if ("30d".equals(range)) {
            days = 30;
        } else if ("90d".equals(range)) {
            days = 90;
        }

        // 生成完整的日期序列
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);

        // 创建日期到数量的映射
        Map<String, Integer> dataMap = new HashMap<>();
        if (rawData != null) {
            for (RegistrationStat data : rawData) {
                if (data != null && data.getDate() != null) {
                    dataMap.put(data.getDate(), data.getCount().intValue());
                }
            }
        }

        // 填充完整的日期序列
        for (int i = 0; i < days; i++) {
            LocalDate currentDate = startDate.plusDays(i);
            String dateStr = currentDate.toString();
            dates.add(dateStr);
            counts.add(dataMap.getOrDefault(dateStr, 0));
        }

        statVo.setDates(dates);
        statVo.setCounts(counts);

        return statVo;
    }

}
